<template>
  <div>
    <el-dialog
      class="dialog-style"
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :append-to-body="true"
      :show-close="false">
      <div slot="title" class="title">
        <el-button class="back" type="text" @click="dialogVisible=false;">返回</el-button>
        <span>招聘录入</span>
      </div>
      <div class="content" v-loading="loading">
        <el-form :model="form" ref="form" label-width="80px">
          <el-form-item label="姓名" prop="intervieweeName" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
            <el-input v-model="form.intervieweeName" style="width: 220px;" :disabled="!canEdit"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="intervieweePhone" 
            :rules="[
              { required: true, message: '请输入手机号', trigger: 'blur' },
              { pattern: /^[1]([3-9])[0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
            ]">
            <el-input v-model="form.intervieweePhone" style="width: 220px;" :disabled="!canEdit"></el-input>
          </el-form-item>
          <el-form-item :label="dict.name" v-for="dict in dictList" :key="dict.id">
            <el-select v-model="form.intervieweeEducation" :placeholder="'请选择'+dict.name" style="width: 220px;" v-if="dict.id === '1326795739818127362'">
              <el-option :label="theme.name" :value="theme.name" v-for="theme in dict.children" :key="theme.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="form.intervieweeSex" :disabled="!canEdit">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker v-model="form.intervieweeBirth" type="date" value-format="yyyy-MM-dd" style="width: 220px;" :disabled="!canEdit"></el-date-picker>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="form.intervieweeAge" style="width: 220px;" type="number" min="0" max="1000" @wheel.native.prevent="stopScrollFun($event)" :disabled="!canEdit || !!form.intervieweeBirth"></el-input>
          </el-form-item>
          <el-form-item label="面试时间" prop="intervieweeInterviewTime" :rules="[{ required: true, message: '请选择面试日期', trigger: 'change' }]">
            <el-date-picker v-model="form.intervieweeInterviewTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" default-time="10:00:00" style="width: 220px;" :disabled="!canEdit"></el-date-picker>
          </el-form-item>
          <el-form-item label="部门" prop="intervieweeDeptId" :rules="[{ required: true, message: '请选择部门', trigger: 'change' }]">
            <el-select v-model="form.intervieweeDeptId" style="width: 220px;" ref="intervieweeDeptIdSelected" :disabled="!canEdit" @change="resetIntervieweeJob">
              <el-option :label="dept.deptName" :value="dept.id" v-for="dept in departmentList" :key="dept.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="岗位" prop="intervieweeJobId" :rules="[{ required: true, message: '请选择岗位', trigger: 'change' }]">
            <el-select v-model="form.intervieweeJobId" style="width: 220px;" ref="intervieweeJobIdSelected" :disabled="!canEdit">
              <el-option :label="job.jobName" :value="job.id" v-for="job in jobList" :key="job.id"></el-option>
            </el-select>
          </el-form-item>
          <div v-if="!form.id">
            <div v-for="(step, index) in modelList" :key="step.id">
              <el-form-item :label="index === 0 ? '接待人' : step.stepName" v-if="index < 4" :rules="index === 0 || index === 3 ? [{ required: true, message: '', trigger: 'blur' }] : []">
                <div class="select-btn" @click="showSelectUserDialog(step, index)" v-if="!step.candidatesId"><span><i class="el-icon-plus"></i></span>选择</div>
                <div class="select-btn" style="padding: 0;" v-if="step.candidatesId">{{step.candidatesName}}<div class="del" @click="delMember(step)">移除</div></div>
              </el-form-item>
            </div>
          </div>
          <el-form-item label="备注">
            <el-input v-model="form.intervieweeRemark" type="textarea" placeholder="请输入薪资福利等" rows="6" :disabled="!canEdit"></el-input>
          </el-form-item>
          <el-form-item label="简历">
            <input ref="uploadInput" style="display:none;" type="file" @change="uploadFile($event)" multiple>
            <el-button type="text" @click="$refs.uploadInput.click()" class="upload-btn" :disabled="!canEdit">上传简历（只能是PNG/JPG）</el-button>
          </el-form-item>
          <div class="resume" v-if="form.intervieweeResume && form.intervieweeResume.length > 0">
            <el-card v-for="(img, imgIdx) in form.intervieweeResume" :key="imgIdx" style="overflow: auto;">
              <img :src="img" style="width: auto; height: auto; max-width: 100%; max-height: 100%;">
              <i class="el-icon-close" @click="delFile(imgIdx)" v-if="canEdit"></i>
            </el-card>
          </div>
          <div class="btn-group">
            <el-button @click="dialogVisible = false" size="mini">取消</el-button>
            <el-button type="primary" @click="submitForm" size="mini" v-if="canEdit">保存</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
      title="选择用户"
      :close-on-click-modal="false"
      :visible.sync="userDialogVisible"
      width="520px"
      :append-to-body="true">
      <div>
        <el-tag type="info" v-for="user in curStepUserList" :key="user.emplId" style="margin-right: 20px; cursor: pointer;" @click="chooseUser(user)">{{user.name}}</el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import {dateUtil} from '@/utils/dateUtil'
export default {
  data () {
    return {
      dialogVisible: false,
      departmentList: [],
      jobListInit: [],
      form: {
        intervieweeName: '',          //面试人name
        intervieweePhone: '',         //面试人电话
        intervieweeSex: 1,           //面试者性别（1：男，2：女）
        intervieweeAge: 0,           //面试者年龄
        intervieweeBirth: '',         //面试者出生日期
        intervieweeJobId: '',         //面试者应聘岗位id
        intervieweeJobName: '',       //面试者应聘岗位name
        intervieweeDeptId: '',        //部门id
        intervieweeDeptName: '',      //部门name
        intervieweeInterviewTime: '', //面试者面试时间
        intervieweeResume: [],        //面试简历url
        intervieweeRemark: '',        //备注
        intervieweeCancelRemark: '',
        intervieweeEducation: '', //学历
      },
      stepList: [],
      stepListInit: [],
      process: {       //流程需要数据
        name: '',      //流程名称（格式 面试人姓名:电话号码）
        remark: '',    //流程备注
        modelId: '',   //流程模型 固定填 3
      },
      loading: false,
      modelList: [],
      userDialogVisible: false,
      curStepUserList: [],
      curIndex: 0,
      dictList: [], //学历，从字典获取
    };
  },
  mixins: [dingMixin],
  watch: {
    getNameAndPhone: {
      handler() {
        this.getHistoryIntervieweeList()
      },
      deep: true
    },
    getAgeByBirthday() {
      this.getAge(this.getAgeByBirthday);
    },
    getInterviewTime(value) {
      if(value && !this.form.id) {
        let timestamp = Date.parse(value.substring(0, 10));
        let curTimestamp = Date.parse(dateUtil.thisDay());
        if(curTimestamp - timestamp > 0) {
          this.form.intervieweeInterviewTime = null
          return this.$message.error("面试时间不能早于今天")
        }
      }
    }
  },
  computed: {
    jobList() {
      return !this.form.intervieweeDeptId ? this.jobListInit : this.jobListInit.filter(item => { return item.jobDepartmentId === this.form.intervieweeDeptId })
    },
    getNameAndPhone() {
      return {
        intervieweeName: this.form.intervieweeName,
        intervieweePhone: this.form.intervieweePhone
      }
    },
    getAgeByBirthday() {
      return this.form.intervieweeBirth
    },
    getInterviewTime() {
      return this.form.intervieweeInterviewTime
    },
    canEdit() {
      return (this.form.id && this.form.intervieweeStatus !== '-10' && this.form.process.status !== 10) || !this.form.id
    }
  },
  mounted () {
    this.getDictList()  //获取字典中学历
    this.getJobList()
    
  },
  methods: {
    //禁止滚动
    stopScrollFun(evt) {
      evt = evt || window.event;
      if(evt.preventDefault) {
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        evt.cancelBubble=true;
        evt.returnValue = false;
      }
      return false;
    },
    async getHistoryIntervieweeList() {
      let list = await this.$httpN.postB('recruitment/hrrecruitmentinterviewee/intervieweeList', this.getNameAndPhone)
      if(list.length > 0 && ((!!this.form.id && list[0].id !== this.form.id) || !this.form.id)) {
        return this.$message({ message: '注意哦,该面试者已存在档案中', type: 'warning'})
      }
    },
    //获得部门列表,岗位列表
    async getJobList() {
      let list = await this.$httpN.postB('recruitment/hrrecruitmentjob/list');
      if(!list) return
      //供table筛选
      list.forEach( item => {
        item.text = item.deptName;
        item.value = item.id
      })
      let ids = list.filter( item => { return item.deptPid === '' }).map( item => {return item.id} )
      this.departmentList = list.filter( item => { return ids.includes(item.deptPid) })
      let jobArr = [];
      this.departmentList.forEach( dept => {
        if(dept.jobVO && dept.jobVO.length > 0) jobArr.push(...dept.jobVO)
      })
      this.jobListInit = JSON.parse(JSON.stringify(jobArr))
    },
    async init(id) {
      formUtil.resetData(this.form);
      let modelList = await this.$httpN.postB('hr/recruitment/model/info?id=3')
      modelList.modelSteps.forEach(item => {
        item.usersArr = []
        if(item.candidatesId !== '') {
          this.getUserDingIdByRoleId(item)
          item.candidatesId = ''
          item.candidatesIdsArr = []
          item.candidatesName = ''
          item.candidatesNamesArr = []
        }
      })
      this.modelList = modelList.modelSteps
      if(!id) {
        this.form.intervieweeSex = 1;
        this.stepList = this.modelList;
        this.stepListInit = JSON.stringify(this.stepList)
      } else {
        this.form = await this.$httpN.postB('recruitment/hrrecruitmentinterviewee/info', {id: id})
        this.form.intervieweeResume = this.form.intervieweeResume === '' ? [] : JSON.parse(this.form.intervieweeResume)
        this.form.intervieweeInterviewTime = this.getStandardTime(this.form.intervieweeInterviewTime)
        this.form.process.stepList.forEach(item => {
          item.candidatesIdsArr = item.candidatesId === '' ? [] : item.candidatesId.split(",")
          item.candidatesNamesArr = item.candidatesName === '' ? [] : item.candidatesName.split(",")
        })
        this.stepList = this.form.process.stepList
        this.stepListInit = JSON.stringify(this.stepList)
      }
      if(this.$refs.form) this.$refs.form.clearValidate();
      this.dialogVisible = true
    },
    async getUserDingIdByRoleId(item){
      let roleIdArr = item.candidatesId.split(',')
      let data = await this.$httpN.postB('sys/user/listUserByRoleIds', roleIdArr, false)
      let idsArr = []
      let userArr = []
      roleIdArr.forEach( role => {
        data[role].forEach( dingUser => {
          if(!idsArr.includes(dingUser.emplId)) {
            idsArr.push(dingUser.emplId);
            userArr.push(dingUser)
          }
        })
      })
      item.usersArr = userArr
    },
    //日期后台返回cst格式转为gmt格式
    getStandardTime(strDate) {
      if(null === strDate || "" === strDate){
        return "";
      }
      var dateStr=strDate.trim().split(" ");
      var strGMT = dateStr[0]+" "+dateStr[1]+" "+dateStr[2]+" "+dateStr[5]+" "+dateStr[3]+" GMT+0800";
      var date = new Date(Date.parse(strGMT));
      var y = date.getFullYear();
      var m = date.getMonth() + 1;  
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();  
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();  
      minute = minute < 10 ? ('0' + minute) : minute;
      var second = date.getSeconds();
      second = second < 10 ? ('0' + second) : second;
      return y+"-"+m+"-"+d+" "+h+":"+minute+":"+second;
    },
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if(this.stepList[0].candidatesId === '') return this.$message.error('请选择接待人')
          if(this.stepList[3].candidatesId === '') return this.$message.error('请选择三面面试人')
          this.process = {
            name: this.form.intervieweeName + '（' + this.form.intervieweePhone + '）',
            modelId: '3'
          }
          if(this.form.intervieweeDeptId) this.form.intervieweeDeptName = this.$refs['intervieweeDeptIdSelected'].selectedLabel;
          if(this.form.intervieweeJobId) this.form.intervieweeJobName = this.$refs['intervieweeJobIdSelected'].selectedLabel;
          let data = {
            id: this.form.id || undefined,
            intervieweeName: this.form.intervieweeName,
            intervieweePhone: this.form.intervieweePhone,
            intervieweeSex: this.form.intervieweeSex,
            intervieweeAge: this.form.intervieweeAge,
            intervieweeBirth: this.form.intervieweeBirth,
            intervieweeJobId: this.form.intervieweeJobId,
            intervieweeJobName: this.form.intervieweeJobName,
            intervieweeDeptId: this.form.intervieweeDeptId,
            intervieweeDeptName: this.form.intervieweeDeptName,
            intervieweeInterviewTime: this.form.intervieweeInterviewTime,
            intervieweeResume: this.form.intervieweeResume,
            intervieweeRemark: this.form.intervieweeRemark,
            intervieweeEducation: this.form.intervieweeEducation,
          };
          if(JSON.stringify(this.stepList) !== this.stepListInit && this.form.id) data.stepList = this.stepList.filter(item => item.candidatesId)
          if(!this.form.id) {
            this.stepList.forEach((item, index) => {
              if(index > 3) {
                item.candidatesId = item.usersArr.map(user => user.emplId).join(',')
                item.candidatesName = item.usersArr.map(user => user.name).join(',')
              }
            })
            data.stepList = this.stepList;
            data.process = this.process;
          }
          if (! await this.$httpN.postB(!this.form.id ?'recruitment/hrrecruitmentinterviewee/save' : 'recruitment/hrrecruitmentinterviewee/update', data)) return
          formUtil.submitSuccess('保存成功');
          this.$emit("refresh", this.form.id);
          this.dialogVisible = false;
        }
      });
    },
    selectDingUsers(id, name, ids, names, item, num){
      if(this.form.id && this.form.process.step > item.step) return this.$message.error('该流程已结束，不可更改')
      if(this.form.id && this.form.intervieweeStatus === '-10') return this.$message.error('面试已取消')
      this.complexPicker(num, [], item[ids]).then((data)=>{
        item[ids] = data.map(item => item.emplId);
        item[names] = data.map(item => item.name)
        item[name] = item[names].join(',');
        item[id] = item[ids].join(',')
      })
    },
    async uploadFile(e) {
      this.loading = true;
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.$message.error('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) $this.form.intervieweeResume.push(res.data.url)
          $this.loading = false;
        })
      })
      e.target.value = '';
    },
    delFile(idx){
      this.form.intervieweeResume.splice(idx, 1)
    },
    getAge(birthday) {
      if(birthday) {
        let timestamp = Date.parse(birthday);
        let curTimestamp = Date.parse(dateUtil.thisDay());
        if(curTimestamp - timestamp < 0) {
          this.form.intervieweeBirth = null
          this.form.intervieweeAge = ''
          return this.$message.error("出生日期晚于今天，数据有误")
        } else if(curTimestamp - timestamp < 365*24*60*60*1000) {
          returnAge = 0;
        }
        var birArr = birthday.split("-");
        var birYear = Number(birArr[0]);
        var birMonth = Number(birArr[1]);
        var birDay = Number(birArr[2]);

        var nowYear = new Date().getFullYear();
        var nowMonth = new Date().getMonth() + 1; //记得加1
        var nowDay = new Date().getDate();
        var returnAge;
        
        var ageDiff = nowYear - birYear;
        if (nowMonth == birMonth) {
          var dayDiff = nowDay - birDay;
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          var monthDiff = nowMonth - birMonth;
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
        this.form.intervieweeAge = returnAge;
      }
    },
    resetIntervieweeJob() {
      this.form.intervieweeJobId = '';
      this.form.intervieweeJobName = '';
    },
    showSelectUserDialog(step, index) {
      this.curStepUserList = step.usersArr
      this.curIndex = index
      this.userDialogVisible = true
    },
    delMember(step) {
      step.candidatesId = '';
      step.candidatesName = '';
    },
    chooseUser(user) {
      this.stepList[this.curIndex].candidatesId = user.emplId
      this.stepList[this.curIndex].candidatesName = user.name
      this.userDialogVisible = false
    },
    async getDictList() {
      let {list} = await this.$httpN.postB('hr/dict/list', { pid: '', limit: 999 })
      list.forEach(item => {
        item.children = [];
        this.getSubDictList(item)
      })
      this.dictList = list.filter(item => item.id === '1326795739818127362');
    },
    async getSubDictList(item) {
      let {list} = await this.$httpN.postB('hr/dict/list', { pid: item.id, limit: 999 })
      item.children.push(...list)
    },
  }
}
</script>

<style lang='scss' scoped>
.dialog-style {
  /deep/ .el-dialog__header, /deep/ .el-dialog__body {
    padding: 0;
  }
  .title {
    text-align: center;
    width: 100%;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #DCDFE6;
    position: relative;
    .back {
      position: absolute;
      left: 20px;
      top: 7px;
      cursor: pointer;
    }
  }
  .content {
    padding: 20px;
    height: calc(100vh - 50px);
    overflow: auto;
    .el-form {
      max-width: calc(100% - 226px);
      .select-btn{
        float:left;
        font-weight: normal;
        margin-right: 5px;
        margin-bottom: 10px;
        width: 80px;
        height: 28px;
        border-radius: 30px;
        background: #FAFAFA;
        border: 1px solid #ECECEC;
        position: relative;
        padding-left: 21px;
        line-height: 28px;
        color: #7982A7;
        font-size: 12px;
        text-align: center;
        cursor: pointer;
        span{
          position: absolute;
          top: 1px;
          left: 1px;
          display:block;
          height: 24px;
          width: 24px;
          background: #CACACA;
          color: white;
          border-radius: 50%;
          text-align: center;
          line-height: 24px;
          img{
            width: 24px;
            height: 24px;
            border-radius: 50%;
          }
        }
        .del{
          position: absolute;
          top:0;
          left: 0;
          width: 100%;
          height: 100%;
          border-radius: 30px;
          color: white;
          text-align: center;
          background:rgba(130, 130, 130, 0.9);
          display: none;
        }
        &:hover{
          .del{
            display: block;
          }
        }
      }
      .upload-btn {
        text-decoration: underline;
        font-style: oblique;
      }
      .resume {
        padding-left: 80px;
        width: 100%;
        overflow-x: auto;
        .el-card {
          margin-bottom: 20px;
          position: relative;
          &:hover i {
            display: block;
          }
          i {
            display: none;
            position: absolute;
            right: 10px;
            top: 10px;
            background-color: #409eff;
            color: #FFF;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            cursor: pointer;
          }
        }
      }
    }
    .btn-group {
      position: fixed;
      top: 70px;
      right: 35px;
    }
  }
}
</style>